package com.fotile.weixin.event;

import com.fotile.base.JaxbMapper;
import com.fotile.weixin.event.thread.AutoExpandExcutor;
import com.fotile.weixin.event.thread.ResponseCallable;
import com.fotile.weixin.event.dto.*;
import com.fotile.weixin.work.aes.AesException;
import com.fotile.weixin.work.aes.WXBizMsgCrypt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * 开启通讯录回调事件
 */
public class WorkServletUtil {

    private static Log log = LogFactory.getLog(WorkServletUtil.class);

    public InstructionObject process(HttpServletRequest request, WXBizMsgCrypt wxcpt, long startTimeStamp) throws IOException {
        String sReqMsgSig = request.getParameter("msg_signature");
        String sReqTimeStamp = request.getParameter("timestamp");
        String sReqNonce = request.getParameter("nonce");
        byte[] buffer = new byte[1024 * 1024];
        InputStream inStream=request.getInputStream();
        int length = inStream.read(buffer);
        if(length<0){
            inStream.close();
            return null;
        }
        String requestXml = new String(buffer, 0, length, "UTF-8");
        inStream.close();
        try {
            String sMsg = wxcpt.DecryptMsg(sReqMsgSig, sReqTimeStamp, sReqNonce, requestXml);
//			log.error("回调信息："+sMsg);
            RequestDTO requestDTO = JaxbMapper.fromXml(sMsg, RequestDTO.class);
            ResponseDTO response = new ResponseDTO(requestDTO);
            InstructionObject io = new InstructionObject(requestDTO, response);
            Processor<InstructionObject> processor = InstructionMatcher.match(io);
            FutureTask<InstructionObject> ft = new FutureTask<InstructionObject>(new ResponseCallable(io, processor, startTimeStamp));
            AutoExpandExcutor.execute(ft);
            io = ft.get(4800, TimeUnit.MILLISECONDS);
            return io;
        } catch (Exception e) {
            log.error(e);
            return null;
        }

    }

    public void valid(HttpServletRequest request, HttpServletResponse response, WXBizMsgCrypt wxcpt) {

        try {
            // 解析出url上的参数值如下：
//            微信加密签名
            String sVerifyMsgSig = request.getParameter("msg_signature");
            // 时间戳
            String sVerifyTimeStamp = request.getParameter("timestamp");
//            随机数
            String sVerifyNonce = request.getParameter("nonce");
            // 随机字符串
            String sVerifyEchoStr = request.getParameter("echostr");
            // 通过检验msg_signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            String sEchoStr; // 需要返回的明文
            sEchoStr = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr);
            response(response, sEchoStr);
        } catch (AesException e) {
            log.error(e);
            response(response, "");
        }
    }
    public void response(HttpServletResponse response, String respText) {
        PrintWriter out;
        response.setCharacterEncoding("utf-8");
        try {
            out = response.getWriter();
            out.print(respText);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
